<template>
 
    <a-spin :spinning="confirmLoading" :style="{height:viewheight+'px'}">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <div id="view" style="display:flex"    >
          <img id="view1" :style="{height:imgheight+'px',width:imgwith+'px'}" :src="'data:image/jpg;base64,' + Frameimg " alt="主摄像头">
          <div id="container" class="down-tree"  style="overflow-y:auto; width:100%;display:flex;flex-wrap:wrap;margin-top:20px;border:1px dashed #d9d5d5;"  > 
            <div :class="'hopic'+index" v-for="(item,index) in imglist" :key="index" style="width:105px;margin:5px"   v-viewer="{movable: false}" >
             
              <img :id="'img'+index" class='pic' width='105px'  height='85px' :src="'data:image/jpg;base64,'+item" @contextmenu.prevent="onContextmenu"    />
            
            
            </div>
            
  
          </div>  
        </div>
        

        <div class="table-operator"> 
          <!-- <a-checkbox v-model:checked="rectifying" @change="OpenDeskew" style="margin-left: 10px;">纠偏裁边</a-checkbox> -->
          <a-button @click="OpenCamera()" :loading="openLoading" type="primary" icon="file-image" style="margin-left: 10px;">打开高拍仪</a-button>
          <a-button @click="close_view1()" :loading="closeLoading" icon="file-excel">关闭高拍仪</a-button> 
          <a-button @click="rotate()" type="primary" icon="redo">旋转</a-button> 
          <a-button @click="GrabImage()" :loading="GrabLoading" type="primary" icon="picture" :disabled="hubmit"   >拍照</a-button>  
          <a-button @click="handleOk()"  :loading="iconLoading" type="danger" icon="check-square">提交</a-button>   
        </div>
        <a-modal v-model:visible="isLoading" :footer="null" :keyboard="false" :maskClosable="false" :closable="false" 
        :width="100"
        :height="100"    wrapClassName="web">
          <div style="text-align:center;margin-top:20px;" >
            <a-spin :size="large"/>
            <p>loading...</p> 
          </div>
        </a-modal>

        <!-- PDF --> 
        <!-- 设备 --> 
        <!-- 操作日志 --> 
      </a-form-model>
   
    </a-spin>
    
</template>

<script>
  import Vue from 'vue'
  import axios from 'axios' 
  import { validateDuplicateValue } from '@/utils/util'
  import Contextmenu from "vue-contextmenujs" 
  import Viewer from 'v-viewer'
  import 'viewerjs/dist/viewer.css'
  import { mapGetters } from 'vuex' 
  Vue.use(Viewer)
  // 全局配置
  Viewer.setDefaults({
    zIndex: 9999, // 图片查看器的层级
    navbar: false, // 隐藏导航栏
    toolbar: {
      zoomIn: true,
      zoomOut: true,
      oneToOne: true,
      reset: true,
      play: true,
      rotateLeft: true, 
      rotateRight: true,
      flipHorizontal: true,
      flipVertical: true,
    },
  }) 
  Vue.use(Viewer)
  Vue.use(Contextmenu);
  export default {
    name: "LebCamera",
    components: {  
    },
    data () {
      return {  
        isLoading:false,
        iconLoading:false,
        openLoading:false,
        closeLoading:false,
        GrabLoading:false,
        hubmit:true,
        imgwith:350,
        imgheight:400,
        Frameimg:"", //Frame图片
        rectifying:false,//摄像头纠偏
        autocamera:false,//自动拍照
        quality:0,//图片质量
        ColorMode:0,//色彩模式
        viewheight:450,
        disabled:false,
        title:"操作",
        qualitylist:[
          {id:0,name:'默认质量'},
          {id:1,name:'高质量'},
          {id:2,name:'较高质量'},
          {id:3,name:'中等质量'},
          {id:4,name:'较差质量'},
          {id:5,name:'差质量'}, 
        ],
        ColorModeList:[
          {id:0,name:'彩色模式'},
          {id:1,name:'灰色模式'},
          {id:2,name:'黑白模式'},
          {id:3,name:'白纸印章'},
          {id:4,name:'去除背景'}, 
        ],
        width:800,
        rotatv:0,
        modelvisible: false,
        visible: true,
        model:{
         },
        labelCol: {
          xs: { span: 4 },
          sm: { span: 9 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
        twolabelCol: {
          xs: { span: 4 },
          sm: { span: 5 },
        },
        twowrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 },
        }, 
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/ml/daMl/add",
          edit: "/ml/daMl/edit",
        },
        expandedRowKeys:[],
        pidField:"pid",
        imglist:[],
        timer: "",
  
      }
    },
    created () {
       //备份model原始值  
       this.modelDefault = JSON.parse(JSON.stringify(this.model));
       console.log("打开高拍仪");
        let timer = setTimeout(() => {
          this.close_view1();
          
          this.OpenCamera();
        }, 3000)
       
    },
    methods: {
      ...mapGetters(["lebcamera"]),  
      show(){

        this.iconLoading=false;
        this.openLoading=false;
        this.closeLoading=false;
        this.GrabLoading=false;
        // this.hubmit=true;
        this.imglist = [];
        console.log("show");
        // let timer = setTimeout(() => {
        //   this.close_view1();
          
        //   this.OpenCamera();
        // }, 3000)

      }, 
      getUrlBase64(url, ext, callback) {
          var canvas = document.createElement("canvas");   //创建canvas DOM元素
          var ctx = canvas.getContext("2d");
          var img = new Image;
          img.crossOrigin = 'Anonymous';
          img.src = "data:image/jpg;base64,"+url;
          img.onload = function () { 
              // if(img.width>img.height){
              //   canvas.width = img.height-100;
              //   canvas.height = img.width-100;
              //   ctx.rotate((90 * Math.PI) / 180);
              //   ctx.drawImage(img, 40, -img.height-100, img.width-100, img.height-100); 
              // }else{
                // canvas.height = img.height-100; //指定画板的高度,自定义
                // canvas.width = img.width-100; //指定画板的宽度，自定义 
                // ctx.drawImage(img, -40, -40, img.width-40, img.height-40); //参数可自定义

                canvas.height = img.height; //指定画板的高度,自定义
                canvas.width = img.width; //指定画板的宽度，自定义 
                ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
              // }
              var dataURL = canvas.toDataURL("image/" + ext);
              callback.call(this, dataURL); //回掉函数获取Base64编码
              canvas = null;
          };
         
      },
      onContextmenu(event) { 
        let id = event.srcElement.attributes[0].value;

        this.$contextmenu({
            items: [
              {
                label: "预览(B)",
                onClick: () => { 
                  console.log("返回(B)"); 

                  const viewer = this.$el.querySelector('.hopic'+id.replace("img","")).$viewer
                  viewer.show()
                }
              },
              { 
                label: "删除(F)",
                onClick: () => { 
                  console.log("返回(B)");
                  this.imglist.splice(id.replace("img",""),1);
                }
              },   
            ],
            event,
            //x: event.clientX,
            //y: event.clientY,
            customClass: "class-a",
            zIndex: 9999,
            minWidth: 230
          });
          return false; 
      },

      deleteimg(index){
        this.imglist.splice(index,1);
      },
      start(){
        this.timer = setInterval(this.getFarme, 2000); // 注意: 第一个参数为方法名的时候不要加括号;
      },
      getRotate(){
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getRotate", '').then((res)=>{
            if (res.data.returnCode == 0){
                console.log("返回角度",res);
               switch(res.data.data){
                    case 0: this.imgwith = 600; this.imgheight = 400; break;
                    case 1: this.imgwith = 350; this.imgheight = 400; break;
                    case 2: this.imgwith = 600; this.imgheight = 400; break; 
                    case 3: this.imgwith = 350; this.imgheight = 400; break; 
               }
            }
        }) 
      },
      getFarme(){
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getFrame", '').then((res)=>{
            if (res.data.returnCode == 0){
               this.Frameimg = res.data.data.img;
            }
        }) 
      },
      OpenDeskew(){ 
        if (this.rectifying == false) { 
            this.OpenCorrect("0");
        } else { 
            this.OpenCorrect("1");
        }
      },     
      handleOk(){         
        if (this.imglist.length == 0){
          this.$message.error("请先拍照");
          return
        } 
        this.iconLoading = true;
        // this.hubmit = true;
        console.log("提交");
        this.$emit('ok','carmera',this.imglist) 
      },
      OpenCorrect(lx){ 
        axios.get(window._CONFIG['LinuxGPYUrl']+"/EnableDeskImage?enable="+lx, '').then((res)=>{
           if (res.data.returnCode != 0){
            this.$message.error(res.data.returnMsg)
           }
        })
      }, 
      // 打开主头视频
      OpenCamera(){
        this.openLoading = true;
        this.isLoading = true;
        axios.get(window._CONFIG['LinuxGPYUrl']+"/GetDeviceCount", '').then((res)=>{ 
           if (res.data.returnCode == 0){
              if (res.data.data > 0){
                this.getRotate();
                this.rectifying = true;
                this.OpenCorrect(1);
                axios.get(window._CONFIG['LinuxGPYUrl']+"/StartPreview?dev_idx=0&res_id=0&pixfmt=", '').then((res)=>{
                    console.log("启动高拍仪",res)
                    if (res.data.returnCode == 0){ 
                         this.start();
                         this.openLoading = false;
                         this.isLoading = false;
                         this.hubmit = false;
                    }else{
                      this.openLoading = false; 
                      this.isLoading = false; 
                    }
                }) 
              }else{
                this.openLoading = false;  
                this.isLoading = false;
              }
           }else{
               this.$message.error("打开高拍仪失败！")
               this.openLoading = false;  
               this.isLoading = false;
           }
        }) 
      },
      // 关闭主头视频
      close_view1(){  
        this.closeLoading = true;
        axios.get(window._CONFIG['LinuxGPYUrl']+"/StopPreview?dev_idx=0", '').then((res)=>{
           this.closeLoading = false;
           if (res.data.returnCode == 0){
              console.log("关闭主头视频")
              clearInterval(this.timer);
              this.hubmit = true;
           }
        }) 
      },

      rotate(){
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getRotate", '').then((res)=>{
           if (res.data.returnCode == 0){
                let data = res.data.data;
                var new_rotate = parseInt(res.data.data) + 1;
                new_rotate = new_rotate > 3?0:new_rotate;
                switch(new_rotate){
                    case 0: this.imgwith = 600; this.imgheight = 400; break;
                    case 1: this.imgwith = 350; this.imgheight = 400; break;
                    case 2: this.imgwith = 600; this.imgheight = 400; break; 
                    case 3: this.imgwith = 350; this.imgheight = 400; break; 
                }
                axios.get(window._CONFIG['LinuxGPYUrl']+"/Rotate?count=" + new_rotate, function(res){
                    if(res.data.returnCode != 0){ 
                       this.$message.error(res.data.returnMsg);
                    }
                });
           }
        })    
      },     
      close () {
        this.$emit('close');
        this.visible = false;
        this.$refs.form.clearValidate()
      }, 
      handleCancel () {
        this.close()
      },
      submitSuccess(formData,flag){
        if(!formData.id){
          let treeData = this.$refs.treeSelect.getCurrTreeData()
          this.expandedRowKeys=[]
          this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
          this.$emit('ok',formData,this.expandedRowKeys.reverse());
        }else{
          this.$emit('ok',formData,flag);
        }
      },
      getExpandKeysByPid(pid,arr,all){
        if(pid && arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].key==pid){
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'],all,all)
            }else{
              this.getExpandKeysByPid(pid,arr[i].children,all)
            }
          }
        }
      }, 
      GrabImage(){ 
        let that = this;
        that.isLoading = true;
        that.GrabLoading = true;
        axios.get(window._CONFIG['LinuxGPYUrl']+"/getPic?quality=80", '').then((res)=>{
           

           if (res.data.returnCode == 0){ 

                // that.getUrlBase64(res.data.data.img, 'jpg', function (base64) {  
                    that.GrabLoading = false;
                    that.isLoading = false;
                    let base64 = res.data.data.img;
                    console.log(base64)
                    that.imglist.push(base64)   
                    // 获取设置了滚动属性的div标签
                    const div = document.getElementById('container');
                    // 设置滚动的顶点坐标为滚动的总高度
                    div.scrollTop = div.scrollHeight + 50; 
                // });
                
                
           }else{
            that.message.error("拍照失败");
            that.GrabLoading = false;
            that.isLoading = false;
           }
        }) 



        
      }
      
    }
  }


  // 传递图片base64，缩略图框生成图片用来显示,并添加到PDF队列
  function add_img(img_base64){
    let img = document.createElement('img');
    img.id = 'hu' + String(Math.random());
    img.src = "data:image/jpg;base64," + img_base64;
    img.oncontextmenu = showOperation;
    img.style.width = '80px';
    img.style.height = '80px';
    document.getElementById('my_thumbnail').appendChild(img)
  }
</script>
<style>
/* 全局 */
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 10px;
}
/* 视频预览 */
#view1, #view2{
  width: 300px; 
  height: 212px;  
  border: 1px solid rgba(185, 181, 181, 0.404);
  margin-right: 5px;
}
/* 缩略图 */
#suoluetu{
  width: 100%; 
  border: 1px solid rgba(185, 181, 181, 0.404);
}
#suoluetu img{
  margin-right: 10px;
}
/* 操作按钮 */
#myactive{
  border: 1px solid yellowgreen;
  margin-top: 10px;
  padding: 10px 5px;
}
/* 操作日志 */
#mylog{
  border: 1px solid black;
  padding: 10px;
  margin-top: 10px;
  overflow: auto;
}
.ant-spin-container{
  height: 100%;
}
.ant-form ant-form-horizontal{
  height: 100%;
}
.table-operator{
  margin-top: 10px;
  text-align: right; } 
/* .hopic{
  .delete-img { 
  }
  &:hover {
    .delete-img {
      display: block;
      position: absolute;
      width: 105px;
      height: 85px;
      line-height: 85px;
      margin-top:-85px;
      background: rgba(59, 60, 61, 0.5);  
      cursor: pointer;
      text-align: center;
      i {
        
        display: block;
        font-size: 24px;
        color: white;
      }
    }
  }
} */
</style>